# This file is part of Sonedyan.
#
# Sonedyan is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation;
# either version 3 of the License, or (at your option) any
# later version.
#
# Sonedyan is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2009-2012 Jimmy Dubuisson <jimmy.dubuisson@gmail.com>

# 
# compute mean correlation of cycles
#

library(igraph)
library(hash)

# get set of cycle path of length 'l' passing through vertex 'v'
get.vertex.cycles <- function(g, v, l)
{
	nv <- neighbors(g, v, mode = "in")
	sp <- get.all.shortest.paths(g, v, nv, mode = "out")
	s <- sapply(sp, length)
	# return paths whose length equals l
	sp[which(s == l)]
}

# get set of unlabeled edge indexes
get.unlabeled.edge.indexes <- function(g, eids)
{
	h <- hash(eids, 0:(length(eids) - 1))
	reids <- c()

	for (u in E(g)$id)
	{
		if (!has.key(u, h))
		{	 
			reids <- append(reids, u)
		}
	}

	E(g)[E(g)$id %in% reids]
}

# get mean cycle correlation
get.mean.cycle.correlation <- function(core, cormat, cycle)
{
  names <- V(core)[cycle]$name
  mean(cormat[names, names])
}

# get mean correlation of cycles of length 'l'
get.mean.correlation <- function(core, cormat, l)
{
	total <- 0
	counter <- 0

	for (v in V(core))
	{
		cs <- get.vertex.cycles(core, v, l)
	
        	if (length(cs) > 0)
		{
			# for all cycles found
			for (c in c(1:length(cs)))
			{
				cycle <- cs[[c]]
				
				# complete vector of nodes with starting node
				#cycle <- append(cycle, cycle[1])

				total <- total + get.mean.cycle.correlation(core, cormat, cycle)
				counter <- counter + 1
			}
		}
	}

	total / counter
}

# args[3] -> <max-cycle-length>
args <- commandArgs()
n <- args[3]

core <- read.graph(file = "fa-core-graphml.xml", format = "graphml")

# load the subset of 1grams
words <- read.table("fa-core-1gram-subset-words.txt")

# load matrix of core normalized time series (subset of 1grams)
mat <- read.table("normalized-fa-core-1gram-subset-words.csv", header = FALSE)

# set mat row names
rownames(mat) <- words$V1

# get transpose of matrix
mat2 <- t(mat)
# compute correlation matrix
cormat <- cor(mat2, method = "spearman")

print(mean(cormat))

# set cormat row/col names
rownames(cormat) <- words$V1
colnames(cormat) <- words$V1

mean <- get.mean.correlation(core, cormat, n)

print(mean)
